package com.zzh.zzhaiagent.websocket;

import cn.hutool.core.net.url.UrlBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.InetSocketAddress;

/**
 * @author: zzh
 * @date: 2024/12/18 09:44:39
 * @version: 1.0
 * 获取请求参数的handler websocket请求链处理Handler
 */
@Slf4j
public class NettyRequestParamsHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpRequest){
            HttpRequest request = (HttpRequest) msg;
            // hutool工具类获取请求参数
            UrlBuilder urlBuilder = UrlBuilder.ofHttp(request.uri());
            CharSequence token = urlBuilder.getQuery().get("token");
            if (token!= null){
                // 解析token
                String stringToken = token.toString();
                //保存token到Channel中去
                ctx.channel().attr(AttributeKey.valueOf("token")).set(stringToken);
            }
            // 更改uri，去掉token参数
            request.setUri(urlBuilder.getPath().toString());

            // 获取IP信息
            String ip  = request.headers().get("X-Real-IP");
            if (StringUtils.isEmpty(ip)) {//如果没经过nginx，就直接获取远端地址
                InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
                ip = address.getAddress().getHostAddress();
            }
            // 保存IP到Channel中去
            ctx.channel().attr(AttributeKey.valueOf("ip")).set(ip);
            // 移除本handler 防止重复处理 ip????token不是要一直处理吗？
            ctx.pipeline().remove(this);
        }
        // 继续处理websocket消息
        ctx.fireChannelRead(msg);
    }

}
